package com.mentalhealthplatform.global.rbac.service.relation;

import com.mentalhealthplatform.global.rbac.model.Permission;
import com.mentalhealthplatform.global.rbac.model.Role;
import com.mentalhealthplatform.global.rbac.repository.PermissionRepository;
import com.mentalhealthplatform.global.rbac.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RolePermissionService {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    // 为角色绑定权限
    public Role bindPermissionsToRole(Long roleId, List<Long> permissionIds) {
        Role role = roleRepository.findById(roleId)
                .orElseThrow(() -> new RuntimeException("Role not found"));

        List<Permission> permissions = permissionRepository.findAllById(permissionIds);
        if (permissions.isEmpty()) {
            throw new RuntimeException("Permissions not found");
        }

        // 将 List<Permission> 转换为 Set<Permission>
        Set<Permission> permissionSet = new HashSet<>(permissions);

        role.setPermissions(permissionSet);
        return roleRepository.save(role);
    }



    public Set<Permission> getPermissionsForRole(Long roleId) {
        Role role = roleRepository.findById(roleId)
                .orElseThrow(() -> new RuntimeException("Role not found with ID: " + roleId));
        return role.getPermissions();
    }

    public List<Map<Role, Set<Permission>>> getRolesWithPermissionsByIds(List<Long> roleIds) {
        List<Map<Role, Set<Permission>>> rolesWithPermissions = new ArrayList<>();

        for (Long roleId : roleIds) {
            Role role = roleRepository.findById(roleId)
                    .orElseThrow(() -> new RuntimeException("Role not found with ID: " + roleId));
            Map<Role, Set<Permission>> rolePermissionsMap = new HashMap<>();
            rolePermissionsMap.put(role, getPermissionsForRole(roleId));
            rolesWithPermissions.add(rolePermissionsMap);
        }

        return rolesWithPermissions;
    }

}
